package com.usian.admin.filter;

import com.usian.admin.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Log4j2
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获得请求体和响应体
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //判读是否是登录请求
        if (request.getURI().getPath().contains("/login/in")) {
            //放行
            return chain.filter(exchange);
        }

        //获取请求头中的jwt信息
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");

        try {
            //判断token是否存在
            if (StringUtils.isEmpty(token)) {
                //不存在，返回一个错误信息
                response.setStatusCode(HttpStatus.MULTI_STATUS);
                return response.setComplete();
            }

            Claims claims = AppJwtUtil.getClaimsBody(token);
            int result = AppJwtUtil.verifyToken(claims);
            if (result == 0 || result == -1) {
                //符合，则在头部重新设置id
//            String id =(String)claims.get("id");
//            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
//                httpHeaders.add("userId",id);
//            }).build();

                Integer id = (Integer) claims.get("id");
                ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                    httpHeaders.add("userId", id.toString());
                }).build();
                exchange.mutate().request(serverHttpRequest).build();
            }
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            return response.setComplete();
        }
        //放行
        return chain.filter(exchange);


    }

    @Override
    public int getOrder() {
        return 0;
    }
}
